﻿using System;
using System.Timers;
using System.Windows;
using _3DTicTacToe.Core;
using _3DTicTacToe.Net;

namespace _3DTicTacToe
{
    internal partial class ClientConnectingWindow : Window
    {
        private readonly TConnection _connection;
        private readonly Player _localPlayer;
        private readonly string _host;
        private readonly Introduction _introduction;
        private readonly Timer _timeoutTimer;

        private bool _starting;

        public ClientConnectingWindow(TConnection connection, Player localPlayer, string host)
            :this()
        {
            _connection = connection;
            _localPlayer = localPlayer;
            _host = host;
            hostLabel.Content += _host;

            _introduction = new Introduction(connection, localPlayer);
            _timeoutTimer = new Timer(10000); // timeout after 10 seconds

            _timeoutTimer.Elapsed += OnTimeout;
            _timeoutTimer.Start();

            _introduction.OnIntroductonComplete += OnIntroductionComplete;
            _introduction.Introduce();
        }

        public ClientConnectingWindow()
        {
            InitializeComponent();
        }

        void OnIntroductionComplete(Player remotePlayer)
        {
            Action a = () =>
                           {
                               new NetLobbyWindow(_connection, _localPlayer, remotePlayer).Show();
                               _starting = true;
                               Close();
                           };
            Dispatcher.Invoke(a, null);
        }

        void OnTimeout(object sender, ElapsedEventArgs e)
        {
            Action a = () =>
                           {
                               _timeoutTimer.Stop();
                               MessageBox.Show(string.Format("Unable to connect to {0}", _host), "Unable to connect!",
                                               MessageBoxButton.OK,
                                               MessageBoxImage.Error);
                               Close();
                           };
            Dispatcher.Invoke(a, null);
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            _timeoutTimer.Stop();
            _timeoutTimer.Dispose();

            if (_starting) return;

            _introduction.Abort();
            _connection.Shutdown(string.Empty);

            new StartWindow().Show();
        }
    }
}
